use yew::prelude::*;
use yew_router::prelude::*;

use crate::{
  contexts::{
    CurrentUserActions, CurrentUserContext, CurrentUserDispatchActions,
  },
  Route,
};

#[function_component]
pub fn Header() -> Html {
  let current_user_ctx = use_context::<CurrentUserContext>()
    .expect("Current user context is missing");

  match &current_user_ctx.user {
    Some(user) => {
      let c_current_user_ctx = current_user_ctx.clone();

      let onclick = {
        move |e: MouseEvent| {
          e.prevent_default();

          c_current_user_ctx.dispatch(CurrentUserDispatchActions {
            action_type: CurrentUserActions::LoginFail,
            login_response: None,
            me_response: None,
          });
        }
      };

      html! {
        <>
          <i>{ format!("Welcome user [{}]", user.username) }</i>
          <button {onclick}>{"Logout"}</button>
        </>
      }
    }
    None => html! {
      <Redirect<Route> to={Route::Login}/>
    },
  }
}
